<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Unit extends Backend
{
    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Product.Unit');
    }

    // 查看
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //添加
    public function add()
    {
        if ($this->request->isPost())
        {
            // 获取表单数据
            $params = $this->request->post('row/a');

            // 加校验器
            $result = $this->model->save($params);

            if ($result === false)
            {
                $this->error($this->model->getError());
                exit;
            }

            $this->success();
        }

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row)
        {
            $this->error(__('商品单位不存在'));
        }

        if ($this->request->isPost())
        {
            // 获取表单数据
            $params = $this->request->post('row/a');
            $params['id'] = $ids;

            $result = $this->model->isUpdate(true)->save($params);

            if ($result === false)
            {
                $this->error($this->model->getError());
                exit;
            }

            $this->success();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}